package com.example.mydanmudemo

import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.os.Message
import android.util.AttributeSet
import android.view.View
import android.view.animation.Animation
import android.view.animation.TranslateAnimation
import android.widget.RelativeLayout

class DanmuView : RelativeLayout {
    private var widthPixels = 0
    private var heightPixels = 0
    private var curPos = 0
    private var datas: List<DanmuBean>? = null


    private val handler = @SuppressLint("HandlerLeak")
    object : Handler() {
        override fun handleMessage(msg: Message) {
            addTextView()
            //弹幕出现间隔时间400-700ms
            val randomDelay = (Math.random() * 300 + 400).toInt()
            sendEmptyMessageDelayed(0, randomDelay.toLong())
        }
    }

    constructor(context: Context?) : super(context) {
        init()
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        init()
    }

    fun init() {
        widthPixels = resources.displayMetrics.widthPixels
        heightPixels = resources.displayMetrics.heightPixels
        handler.sendEmptyMessage(0)
    }

    fun setData(datas: List<DanmuBean>?) {
        this.datas = datas
    }

    private fun addTextView() {
        if (curPos == datas!!.size) {  //循环播放
            curPos = 0
        }
        val moveView = MoveView(context, datas!![curPos++])
        addView(moveView)
        moveView.randomVerticalPos(heightPixels)
        startTranslateAnim(moveView)
    }

    /**
     * 设置从右往左移动动画,时间范围是2000-4000毫秒
     * @param view
     */
    private fun startTranslateAnim(view: View) {
        val randomDuration = (Math.random() * 2000 + 7000).toInt()
        val anim = TranslateAnimation(widthPixels.toFloat(), (-widthPixels).toFloat(), 0F, 0F)
        anim.duration = randomDuration.toLong()
        anim.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationStart(animation: Animation) {}
            override fun onAnimationEnd(animation: Animation) {
                removeView(view)
            }

            override fun onAnimationRepeat(animation: Animation) {}
        })
        view.startAnimation(anim)
    }
}